package com.roc.template.mongo.dao.impl;

import com.roc.template.base.PageBean;
import com.roc.template.mongo.base.BaseDaoImpl;
import com.roc.template.mongo.base.BasePageable;
import com.roc.template.mongo.base.PageModel;
import com.roc.template.mongo.dao.UserDao;
import com.roc.template.mongo.model.User;
import com.roc.template.mongo.vo.UserVo;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName RemoteUserDaoImpl
 * @Description: TODO
 * @Author Administrator
 * @Date 2020/8/26 10 32
 * @Version V1.0
 **/
@Repository
public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao {

    @Resource
    private MongoTemplate mongoTemplate;

    public PageBean<User> pageQuery(UserVo userVo) {
        BasePageable basePageable = new BasePageable();
        PageModel pageModel = new PageModel();
        Query infoQuery = new Query(Criteria.where("isDelete").is(false));

        List<Sort.Order> orders = new ArrayList<>();  //排序
        orders.add(new Sort.Order(Sort.Direction.DESC, "createdTime"));
        Sort sort = new Sort(orders);
        if (userVo.getName() != null && !"".equals(userVo.getName())) {
            infoQuery.addCriteria(Criteria.where("userName").regex(".*?" + userVo.getName() + ".*?"));
        }

        if (userVo.getBeginTime() != null && userVo.getEndTime() != null) {
            infoQuery.addCriteria(Criteria.where("beginTime").gte(userVo.getBeginTime()).lte(userVo.getEndTime()));
        }

        pageModel.setPageNum(userVo.getPageNum());
        pageModel.setPageSize(userVo.getPageSize());
        pageModel.setSort(sort);

        basePageable.setPage(pageModel);

        long count = mongoTemplate.count(infoQuery, User.class);

        List<User> inTimeInventories = mongoTemplate.find(infoQuery.with(basePageable), User.class);

        PageImpl<User> itemClasses = new PageImpl<>(inTimeInventories, basePageable, count);
        return new PageBean<>(itemClasses);
    }


    public User findById(String id) {
        Query infoQuery = new Query(Criteria.where("isDelete").is(false).and("id").is(id));
        return mongoTemplate.findOne(infoQuery, User.class);
    }

    public User getByUserName(String userName) {
        Query infoQuery = new Query(Criteria.where("isDelete").is(false).and("userName").is(userName));
        return mongoTemplate.findOne(infoQuery, User.class);
    }

    public User getByPassword(String passWord) {
        Query infoQuery = new Query(Criteria.where("isDelete").is(false).and("passWord").is(passWord));
        return mongoTemplate.findOne(infoQuery, User.class);
    }
}
